package ace.module.upms.core.impl.manager.impl;

import ace.cmp.core.constants.CoreConstant;
import ace.cmp.data.spring.data.jdbc.querydsl.rsql.core.manager.spring.AbstractSpringDtoManager;
import ace.module.upms.api.model.dto.UpmsRoleDto;
import ace.module.upms.core.impl.dao.entity.UpmsRole;
import ace.module.upms.core.impl.dao.repository.UpmsRoleRepository;
import ace.module.upms.core.impl.manager.UpmsRoleManager;
import ace.module.upms.core.impl.manager.cache.UpmsRoleCacheManager;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 角色对象 spring data jdbc querydsl rsql manager implement.
 *
 * @author Caspar
 */
@Slf4j
@AllArgsConstructor
@Component
public class UpmsRoleManagerImpl
    extends AbstractSpringDtoManager<UpmsRole, Long, UpmsRoleDto>
    implements UpmsRoleManager {

  private final UpmsRoleCacheManager upmsRoleCacheManager;
  private final UpmsRoleRepository upmsRoleRepository;

  @Override
  public Map<Long, List<UpmsRoleDto>> getAccountIdAndRoleMapByUpmsAppIdAndIamAccountIdIn(
      Long upmsAppId,
      List<Long> iamAccountIds) {
    Map<Long, List<UpmsRoleDto>> result = new HashMap<>();
    for (Long iamAccountId : iamAccountIds) {
      List<UpmsRoleDto> upmsRoleDtos = this.getByUpmsApIdAndIamAccountId(upmsAppId, iamAccountId);
      result.put(iamAccountId, upmsRoleDtos);
    }
    return result;
  }

  @Override
  public List<UpmsRoleDto> getByUpmsApIdAndIamAccountId(
      Long upmsAppId,
      Long iamAccountId) {
    List<UpmsRole> upmsRoles = upmsRoleCacheManager.getByUpmsApIdAndIamAccountId(upmsAppId, iamAccountId);
    return this.convertToEntityDto(upmsRoles);
  }

  @Override
  public List<UpmsRole> getByUpmsAppIdAndIdInAndDeleteFlagIsFalse(Long upmsAppId, List<Long> ids) {
    return this.upmsRoleRepository.getByUpmsAppIdAndIdInAndDeleteFlag(upmsAppId, ids, CoreConstant.DELETE_FLAG_NOT);
  }

  @Override
  public boolean anyMatch(List<UpmsRole> roles, Long upmsRoleId) {
    return roles.stream().anyMatch(p -> p.getId().equals(upmsRoleId));
  }
}
